
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI;
using Microsoft.Maui.ApplicationModel;
using QuickReportMaui.Model;
using Map = Esri.ArcGISRuntime.Mapping.Map;

namespace QuickReportMaui.Views;

public partial class DrawLocation : ContentPage, IQueryAttributable
{
    public string DrawType { get; set; }
    public DrawLocation()
    {
        InitializeComponent();

    }
    private FeatureLayer FeatureLayer { get; set; }
    public async void ApplyQueryAttributes(IDictionary<string, object> query)
    {
        DrawType = query["type"] as string;
        if (DrawType == "tree")
        {
            Map map = new Map(BasemapStyle.OSMStreets);
            var mapCenterPoint = new MapPoint(116.7963581069489, 36.53729500053177, SpatialReferences.Wgs84);
            map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);
            var serverUri = new Uri("https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/QuickReportMaui/FeatureServer/0");
            FeatureData.ServiceFeatureTable = new ServiceFeatureTable(serverUri);
            this.FeatureLayer = new FeatureLayer(FeatureData.ServiceFeatureTable);
            map.OperationalLayers.Add(this.FeatureLayer);
            myMapview.Map = map;
        }
    }
    private bool isLocation;
    private async void DisplayLocation(object sender, EventArgs e)
    {
        if (isLocation)
        {
            var status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();

            myMapview.LocationDisplay.IsEnabled = status == PermissionStatus.Granted || status == PermissionStatus.Restricted;
            myMapview.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Recenter;
            isLocation = false;
        }
        else
        {
            myMapview.LocationDisplay.IsEnabled = false;
            isLocation = true;
        }
    }

    private async void Submit(object sender, EventArgs e)
    {
        // Get the current map view extent
        Viewpoint currentViewpoint = myMapview.GetCurrentViewpoint(ViewpointType.BoundingGeometry)!;
        // Get the center point of the extent
        MapPoint centerPoint = currentViewpoint.TargetGeometry.Extent.GetCenter();
        var feature = FeatureData.ServiceFeatureTable.CreateFeature();
        feature.Geometry = centerPoint;
        
        FeatureData.Feature = feature;
        await Shell.Current.GoToAsync("addAttachment");
    }
}